'''
Created on Jan 19, 2015

@author: dewey
'''

import tempfile
import os
import sys
import subprocess
import traceback

from PyQt5.QtCore import *
from PyQt5.QtWidgets import *

import pystrat.stratplot as sp

from ui_gen.Ui_pystrat_autochart_options import Ui_PyStratAutochartDialog

SAVEROLE_GLOBAL = "save_global"

ROLE_SAVE_IMAGE = "save_chart_file"
TYPES_FIGURE_OUT = "Portable Document Format (*.pdf)\nScalable Vector Graphics (*.svg)\nPortable Network Graphics (*.png)"

def shellquote(s):
    return "'" + s.replace("'", "'\\''") + "'"

def launchfile(filename):
    if sys.platform.startswith("linux"):
        subprocess.call(["xdg-open", filename])
    elif sys.platform == 'win32':
        os.system('start %s' % shellquote(filename))
    elif sys.platform == 'darwin':
        os.system('open %s' % shellquote(filename))


class PyStratAutoChartDialog(QDialog, Ui_PyStratAutochartDialog):
    
    def __init__(self, parent=None):
        super(PyStratAutoChartDialog, self).__init__(parent)
        self.setupUi(self)
        
        self.tempfiles = None
        self.vdata_list = None
        self.error_function = None
        self.file_out = None
        self.prefs = None
        
        self.combo_format.addItem("Temporary PDF", ".pdf")
        self.combo_format.addItem("Portable Document Format (PDF)", ".pdf")
        self.combo_format.addItem("Scalable Vector Graphics (SVG)", ".svg")
        self.combo_format.addItem("Portable Network Graphics (PNG)", ".png")
        
        self.combo_presetSizes.addItem("Select Preset Size")
        
        self.combo_groupBy.addItem("None", None)
        self.combo_groupBy.addItem("Dataset", sp.GROUP_BY_VDATA)
        self.combo_groupBy.addItem("Location", sp.GROUP_BY_LOCATION)
        
        self.combo_yaxis.addItem("Depth (reversed)", sp.YAXIS_DEPTH_REVERSED)
        self.combo_yaxis.addItem("Depth", sp.YAXIS_DEPTH)
        self.combo_yaxis.addItem("Age (reversed)", sp.YAXIS_AGE_REVERSED)
        self.combo_yaxis.addItem("Age", sp.YAXIS_AGE)
        
    
    def set_tempfiles_list(self, tmplist):
        self.tempfiles = tmplist
    
    def set_vdata(self, project, vdata_list):
        self.project = project
        self.vdata_list = vdata_list
        self.file_out = None
        self.button_selectFile.setText("Select File")
        self.show()
        
    def set_error_function(self, error_function):
        self.error_function = error_function
    
    def set_prefs(self, prefs):
        self.prefs = prefs
    
    @pyqtSlot(int)
    def on_combo_format_currentIndexChanged(self):
        if self.combo_format.currentIndex() == 0:
            self.file_out = None
            self.check_autoOpen.setChecked(True)
            self.check_autoOpen.setEnabled(False)
        else:
            self.check_autoOpen.setEnabled(True)
            if self.file_out:
                #change suffix
                last_period = self.file_out.rfind(".")
                if last_period == -1:
                    no_suffix = self.file_out
                else:
                    no_suffix = self.file_out[:last_period]
                self.file_out = no_suffix + self.combo_format.currentData()
        print("Changing file out to %s" % self.file_out)
    
    @pyqtSlot()
    def on_button_selectFile_clicked(self):
        self.file_out = self.putfile(TYPES_FIGURE_OUT, ROLE_SAVE_IMAGE)
        last_period = self.file_out.rfind(".")
        if last_period == -1:
            self.file_out = self.file_out + self.combo_format.currentData()
        else:
            end = self.file_out[last_period:]
            if end == ".pdf":
                self.combo_format.setCurrentIndex(1)
            elif end == ".svg":
                self.combo_format.setCurrentIndex(2)
            elif end == ".png":
                self.combo_format.setCurrentIndex(3)
            
            
    
    @pyqtSlot()
    def on_buttonBox_accepted(self):
        #gather options into dictionary
        opts = {}
        opts[sp.MULTIPLOT_ROWS] = self.spin_rows.value()
        opts[sp.MULTIPLOT_COLS] = self.spin_cols.value()
        opts[sp.MULTIPLOT_FIGSIZE] = (self.spin_width.value(), self.spin_height.value())
        
        group_by_value = self.combo_groupBy.currentData()
        outfile = self.file_out
        
        try:
            if not outfile:
                outfile = tempfile.mkstemp(self.combo_format.currentData())[1]
                self.tempfiles.append(outfile)
                   
            plot_options = sp.generate_plot_options(self.vdata_list, self.project, group_by_value,
                                                    self.error_function, yaxis=self.combo_yaxis.currentData(), 
                                                    default_series=None)
    
            sp.multiplot_export(plot_options, outfile, opts, savefig_options=None)
            if self.check_autoOpen.isChecked():
                launchfile(outfile)
            
        except Exception as e:
            traceback.print_exc()
            QMessageBox.critical(self, "Error", "Error creating chart: %s" % str(e))
        
        
    def putfile(self, types, saverole):
        if saverole in self.prefs:
            folder = self.prefs[saverole]
        elif SAVEROLE_GLOBAL in self.prefs:
            folder = self.prefs[SAVEROLE_GLOBAL]
        else:
            folder = ""
        
        
        fname_tup = QFileDialog.getSaveFileName(self, "Save File", folder, types)
        if fname_tup:
            fname = fname_tup[0]
            if fname:
                folder = os.path.dirname(fname)
                self.prefs[saverole] = folder
            return fname
        else:
            return None
        
        
        
        